package com.hq.fxh.Utils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;

import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.Modle.UploadImgRes;
import com.hq.fxh.imageLoader.Constant;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import rx.Subscriber;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * /**
 *
 * @author 薛
 * @ClassName
 * @Description :
 * @Created 2017/8/24
 * @Email xlwenhao1858@sina.com
 */


public class UpLoadUtils {
    ArrayList<String> imageUrl;
    ArrayList<String> imagePath;
    String picPath = null;
    int tag;
    Context context;

    UpLoadPicCallBack upLoadPicCallBack;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //上传图片回调
                case 1001:
                    LogUtils.e("回调到了handle");

                    String request = msg.getData().getString("request");
                    if (request.equals("success")) {
                        LogUtils.e("回调到了handle_success");

                        imageUrl.add(msg.getData().getString("picUrl"));
                        int num = msg.getData().getInt("num") + 1;
                        if (num < imagePath.size()) {
                            String picturePath = imagePath.get(num);
                            if (picturePath.equals(picPath)) {
                                LogUtils.e("上传图片和上一张相同");
                            } else {
                                picPath = picturePath;
                                upLoadImg(picPath, num);
                            }
                        } else {
                            LogUtils.e(" 回调到了finish  " + num);
                            upLoadPicCallBack.onFinishCallBack(imageUrl, tag);

                        }

                    } else if (request.equals("error")) {
                        LogUtils.e("回调到了handle_error");

                        int num = msg.getData().getInt("num") + 1;
                        if (num < imagePath.size()) {

                            String picturePath = imagePath.get(num);
                            if (picturePath.equals(picPath)) {
                                LogUtils.e("上传图片和上一张相同");
                            } else {
                                picPath = picturePath;
                                upLoadImg(picPath, num);
                            }

                        } else {
                            LogUtils.e(" 回调到了finish");
                            upLoadPicCallBack.onFinishCallBack(imageUrl, tag);
                        }
                    }

                    break;
            }
        }
    };

    public void startUpLoadPic(Context context, ArrayList<String> picPath, int tag, UpLoadPicCallBack upLoadPicCallBack) {
        this.upLoadPicCallBack = upLoadPicCallBack;
        this.imagePath = picPath;
        this.context = context;
        this.tag = tag;

        imageUrl = new ArrayList<>();

        LogUtils.e("调用了startUpLoad");
        upLoadImg(imagePath.get(0), 0);


    }


    private void upLoadImg(final String picPath, final int upLoadNum) {
        // FIXME: 2017/3/26 上传完成
        String type = "";
        type = String.valueOf(Constant.type + 2);//3 美女 4 搞笑
        if (picPath.endsWith(".gif")) {
            type = "5";//5 gif
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(new File(picPath));
                byte[] bytes = new byte[fileInputStream.available()];
                fileInputStream.read(bytes);
                String twoCodeData = Base64.encodeToString(bytes, Base64.DEFAULT);
                fileInputStream.close();
                UserServiceImpl.uploadImg("videoPic", twoCodeData, "7", new Subscriber<UploadImgRes>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Message msg = new Message();
                        msg.what = 1001;
                        Bundle bundle = new Bundle();
                        bundle.putString("request", "error");
                        bundle.putInt("num", upLoadNum);
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                        upLoadPicCallBack.onErrorCallBack(upLoadNum, e);
                    }

                    @Override
                    public void onNext(UploadImgRes uploadImgRes) {
                        String url = uploadImgRes.getData().getUrl();
                        if (url != null) {
                            Message msg = new Message();
                            msg.what = 1001;
                            Bundle bundle = new Bundle();
                            bundle.putString("request", "success");
                            bundle.putString("picUrl", url);
                            bundle.putInt("num", upLoadNum);
                            msg.setData(bundle);
                            handler.sendMessage(msg);
                        }

                    }


                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Luban.get(context)
                    .load(new File(picPath))                     //传人要压缩的图片
                    .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
                    .setCompressListener(new OnCompressListener() { //设置回调
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件
                            FileInputStream fileInputStream = null;
                            try {
                                fileInputStream = new FileInputStream(file);
                                byte[] bytes = new byte[fileInputStream.available()];
                                fileInputStream.read(bytes);
                                String twoCodeData = Base64.encodeToString(bytes, Base64.DEFAULT);
                                fileInputStream.close();
                                String type = "";
                                type = String.valueOf(Constant.type + 2);//3 美女 4 搞笑
                                if (picPath.endsWith(".gif")) {
                                    type = "5";//5 gif
                                }
                                UserServiceImpl.uploadImg("videoPic", twoCodeData, "7", new Subscriber<UploadImgRes>() {

                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        LogUtils.e("图片上传失败" + e.getMessage());
                                        Message msg = new Message();
                                        msg.what = 1001;
                                        Bundle bundle = new Bundle();
                                        bundle.putString("request", "error");
                                        bundle.putInt("num", upLoadNum);
                                        msg.setData(bundle);
                                        handler.sendMessage(msg);
                                        upLoadPicCallBack.onErrorCallBack(upLoadNum, e);
                                    }

                                    @Override
                                    public void onNext(UploadImgRes uploadImgRes) {
                                        LogUtils.e("图片上传成功");
                                        UploadImgRes.DataBean imagedata = uploadImgRes.getData();
                                        String url = null;
                                        if (imagedata != null) {
                                            url = imagedata.getUrl();
                                        }

                                        if (url != null) {
                                            Message msg = new Message();
                                            msg.what = 1001;
                                            Bundle bundle = new Bundle();
                                            bundle.putString("request", "success");
                                            bundle.putString("picUrl", url);
                                            bundle.putInt("num", upLoadNum);
                                            msg.setData(bundle);
                                            handler.sendMessage(msg);
                                        } else {

                                        }

                                    }

                                });
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过去出现问题时调用
                        }
                    }).launch();    //启动压缩
        }
    }


    public interface UpLoadPicCallBack {
        void onFinishCallBack(ArrayList<String> imageUrl, int tag);

        void onErrorCallBack(int position, Throwable e);
    }
}
